package com.lizba.tips.day2;

import java.io.*;
import java.util.Arrays;
import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @Author: Liziba
 * @Date: 2021/10/23 18:54
 */
public class TryCatchDemo {


    public static void main(String[] args) {
        String path = "D:\\readline.txt";
        String line = readFirstLine(path);
        System.out.println(line);
    }

    /***
     * 读取指定路径文件第一行数据内容
     *
     * @param path 文件路径
     * @return
     */
    public static String readFirstLine1(String path){

        BufferedReader br = null;
        String line = null;
        try {
            br = new BufferedReader(new FileReader(path));
            line = br.readLine();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(br);
        }
        return line;
    }


    /***
     * 读取指定路径文件第一行数据内容 采用 try-with-resources
     *
     * @param path 文件路径
     * @return
     */
    public static String readFirstLine(String path) {

        String line = null;
        try (BufferedReader br = new BufferedReader(new FileReader(path))){
            line = br.readLine();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return line;
    }


    /**
     * 释放资源，需注意资源释放顺序
     *
     * @param closeables
     */
    public static void close(Closeable... closeables) {
       if (Objects.nonNull(closeables)) {
           for (Closeable closeable : closeables) {
               if (Objects.nonNull(closeable)) {
                   try {
                       closeable.close();
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
           }
       }
    }


}
